<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\index\model;

use constant\config;
use think\Db;
use think\Model;
use think\Request;
use app\api\model\PollingModel;
use app\api\model\Aliyunoss;

class Pdf extends Model
{
    
    public function put($order_id, $type)
    {
        
        $io=db('capital')->where(['ordesr_id'=>$order_id, 'types'=>1, 'enable'=>1])->select();
        $ca=db('envelopes')->where(['ordesr_id'=>$order_id, 'type'=>1])->field('give_money,expense,purchasing_discount,purchasing_expense,give_b')->find();
        $cap=array_sum(array_column($io,'to_price'));
        $to_price  =$cap + ($ca['expense'] + $ca['purchasing_expense']) - ($ca['give_money'] + $ca['purchasing_discount']);
        $give_money=!empty($ca['give_money'])?$ca['give_money'] : 0;
        $purchasing_discount=!empty($ca['purchasing_discount'])?$ca['purchasing_discount'] : 0;
        $expense=!empty($ca['expense'])?$ca['expense'] : 0;
        $purchasing_expense=!empty($ca['purchasing_expense'])? $ca['purchasing_expense']  : 0;
        $give_b=!empty($ca['give_b'])? $ca['give_b']  : '暂无';
        $s='';
        $p1='';
        foreach ($io as $k=>$o) {
            if ($o["zhi"] == 1) {
                $o['zhi']="是";
            } else{
                $o['zhi']="否";
            }
            $s.='<tr><td>'.$this->cutChineseString($o['class_b']).'</td><td>'.$o["company"].'</td><td>'.$o["un_Price"].'</td><td>'.$o["square"].'</td><td>'.$o["to_price"].'</td></tr>';
        }
        if (!empty($give_money) && !empty($purchasing_discount) && !empty($expense) && !empty($purchasing_expense)) {
            $p='<div style="text-align: right;font-size: 15px;"><span>主合同优惠金额：</span>' . $give_money . '&nbsp;/元&nbsp;&nbsp;<span ><span>代购合同优惠金额：</span>' . $purchasing_discount . '&nbsp;/元&nbsp;&nbsp;<span ><span>主合同管理费：</span>' . $expense . '&nbsp;/元&nbsp;&nbsp;<span ><span >代购合同管理费：</span>' . $purchasing_expense . '&nbsp;/元&nbsp;&nbsp;<span>合计：</span>' . $to_price . '&nbsp;/元</div>';
        }elseif(!empty($give_money) && !empty($expense)){
            $p='<div style="text-align: right;font-size: 15px;"><span >主合同优惠金额：</span>' . $give_money . '&nbsp;/元&nbsp;&nbsp;<span ><span>主合同管理费：</span>' . $expense . '&nbsp;/元&nbsp;&nbsp;<span >合计：</span>' . $to_price . '&nbsp;/元</div>';
        }elseif(!empty($purchasing_discount) && !empty($purchasing_expense)){
            $p='<div style="text-align: right;font-size: 15px;"><span>代购合同优惠金额：</span>' . $purchasing_discount . '&nbsp;/元&nbsp;&nbsp;<span><span>代购合同管理费：</span>' . $purchasing_expense . '&nbsp;/元&nbsp;&nbsp;<span>合计：</span>' . $to_price . '&nbsp;/元</div>';
        }else{
            $p='<div style="text-align: right;font-size: 15px;"><span>合计：</span>' . $to_price . '&nbsp;/元</div> ';
        }
        $p1='<div style="text-align: left;font-size: 15px;"><span>赠送项目：</span>' . $give_b . '</div>';
        $html=<<<EOF
     

<!DOCTYPE html>
 <div>
      <h1 style="text-align: center;margin-top: 0">成都益鸟科技有限公司</h1>
      <p style="text-align: center;margin-top: 0;font-size: 20px">———维修电子报价单———</p>
      <div style="top: 10px">
<table class="imagetable">
<tr>
    <th >名称</th><th >单位</th><th   >单价</th><th >方量</th><th  >总价</th>
</tr>
$s
</table>
<div >$p1</div>
<div style="padding: 20px">$p</div>

      </div>
</div>
<style>
table.imagetable {
   
   font-size:15px;
    color:#333333;
    border-width: 1px;
    border-color: #999999;
    border-collapse: collapse;
     padding: 8px;
    
    
}
table.imagetable th {
    background:#b5cfd2 ;
    border-width: 1px;
    height: 30px;
    border-color: #999999;
     padding: 8px;
   
   
}
table.imagetable td {
    background:#dcddc0 ;
    border-width: 1px;
     height: 30px;
  padding: 8px;
 border-color: #999999;
}

</style>

EOF;
        require_once ROOT_PATH . 'extend/TCPDF/tcpdf.php';
        $pdf=new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->SetCreator('益鸟');
        $pdf->SetAuthor('益鸟 维修');
        $pdf->SetTitle('基检报价单');
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); //设置页头字体
        $pdf->SetKeywords(', PDF, example, test, guide'); //设置关键词
        $pdf->setPrintHeader(false);
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->setFontSubsetting(false);
        $pdf->SetFont('stsongstdlight', '', 20, true);
        $pdf->AddPage();
        $pdf->setTextShadow(['enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>[196, 196, 196], 'opacity'=>1, 'blend_mode'=>'Normal']);
        $pdf->writeHTMLCell(0, 90, '', '', $html, 0, 1, 0, true, '', true);
        $pas=ROOT_PATHS . '/uploads/PDF/' . $order_id . '.pdf';
        $pdf->Output($pas, 'F');
        
        $ali = new Aliyunoss();
        if (file_exists($pas)) {
            $oss_result = $ali->upload('contract/' . config('city') . '/' . $order_id . time() . '.jpg', $pas);
            if ($oss_result['info']['http_code'] == 200) {
                $pa = parse_url($oss_result['info']['url'])['path'];
                if ($type == 2) {
                    $o = db('order')->where(['order_id' => $order_id])->update(['state' => 3, 'update_time' => time(), 'quotation' =>  'https://images.yiniao.co' .$pa]);
                    remind($order_id, 3);
                } elseif ($type == 1) {
                    $o = db('order')->where(['order_id' => $order_id])->update(['quotation' =>  'https://images.yiniao.co' .$pa]);
                }
                if ($o) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
        
    }
    public function shi($order_id)
    {
        
        $io=db('capital')
            ->join('order', 'order.order_id=capital.ordesr_id', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->join('user us', 'order.assignor=us.user_id', 'left')
            ->where(['capital.ordesr_id'=>$order_id])
            ->where('capital.signed',0)
            ->where('capital.enable',1)
//            ->where(['order.state'=>['>', 3]])
            ->where(function ($query) {
                $query->where('capital.types=2')->whereOr('capital.increment=1')->whereOr('capital.up_products=1');
            })
            ->field('capital.*,concat(p.province,c.city,y.county,order.addres) as addres,assignor,us.username,us.mobile,us.store_id,order.telephone,order.contacts,capital.untime,capital.up_products')->select();
        $company_chapter               = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $io[0]['store_id']])->where('status', 1)->where('city_code', config('cityId'))->field('company_chapter,company_name')->find();
        if(empty($company_chapter['company_name'])){
            $company_chapter['company_name']="成都益鸟科技有限公司";
        }
        $company_name=$company_chapter['company_name'];
        if($io){
            $s='';
            $moneyS=0;
            foreach ($io as $k=>$o) {
                $io[$k]['money']  =0;
                
                $capital=db('visa_form')->where('find_in_set(:id,capital_id)', ['id' => $o['capital_id']])->whereNotNull('signing_time')->select();
                
                if ($o['increment'] == 1&& count($capital)==0) {
                    
                    $io[$k]['money'] = 1;
                }
                if ($o['up_products'] == 1 && count($capital)==0) {
                    
                    $io[$k]['money'] = 2;
                }
                if ($o['types'] == 2 && count($capital)==0) {
                    $io[$k]['money'] = 2;
                }
                if ($o['types'] == 2 && $o['increment'] != 1 && count($capital)==0) {
                    $io[$k]['money'] = 2;
                }
                if ($o['types'] == 1 && $o['increment'] == 1 && count($capital)==0) {
                    $io[$k]['money'] = 1;
                }
                
                if ($o['types'] == 2 && $o['increment'] == 1 && count($capital)==0) {
                    $io[$k]['money'] = 3;
                }
                
                if(count($capital) !=0 && $capital[0]['signing_time']<$o['untime']){
                    $io[$k]['money'] = 2;
                }
                if(count($capital) !=0 && $capital[0]['signing_time']>$o['untime']){
                    $io[$k]['money'] = 1;
                }
                if($io[$k]['money']==1  && $o['give']==0){
                    $moneyS+= $o['to_price'];
                }
                if($io[$k]['money']==2  && $o['give']==0){
                    $moneyS-= $o['to_price'];
                }
                
                if ($io[$k]['money']==1 && $o['give']==0) {
                    $o['zhi']="增项";
                } elseif ($io[$k]['money']==2 && $o['give']==0){
                    $o['zhi']="减项";
                } elseif ($io[$k]['money']==1 && $o['give']==2){
                    $o['zhi']="增项(赠送项目)";
                } elseif ($io[$k]['money']==2 && $o['give']==2){
                    $o['zhi']="减项(赠送项目)";
                }else{
                    $o['zhi']="取消";
                }
                $s.='
<div></div>
        <p style=" font-size: 18px;">' . $o['zhi'] . ':</p>
        <p style=" font-size: 18px;">项目名称: <span>' . $o['class_b'] . '</span></p>
    
            <span style=" font-size: 18px;">单位: <span style=" font-size: 18px;">' . $o["company"] . '</span> </span>
            <span  style=" font-size: 18px;">单价: <span style=" font-size: 18px;">' . $o["un_Price"] . '</span> </span>
            <span  style=" font-size: 18px;">单方量: <span style=" font-size: 18px;">' . $o["square"] . '</span> </span>
     
       <p style=" font-size: 18px;">总价: <span style=" font-size: 18px;">' . $o["to_price"] . '</span></p>
        <p style=" font-size: 18px;">备注: <span style=" font-size: 18px;">' . $o["projectRemark"] . '</span></p>
        <div style="border-top-style:dashed; height:1px"></div>
   ';
            }
            $visaFormData = db('visa_form')->where('order_id', $order_id)->where('capital_id',implode(',', array_column($io,'capital_id')))->whereNull('signing_time')->order('id desc')->find();
            
            
            $sign     =db('sign')
                ->where(['order_id'=>$order_id])
                ->find();
            $moneyS=$moneyS+$visaFormData['mainMoney']+$visaFormData['money']-$visaFormData['give_money'];
            $mainMoney=$visaFormData['mainMoney'];
            $money=$visaFormData['money'];
            $give_money=$visaFormData['give_money'];
            $user     =empty($sign['username'])?$io[0]['contacts']:$sign['username'];
            $addres   =$io[0]['addres'];
            $username =$io[0]['username'];
            $phone    =$io[0]['mobile'];
            $telephone=$io[0]['telephone'];
            $time     =date('Y-m-d H:i', time());
            $html     =
                <<<EOF
<html>
<div style="width: 30%">

    <h3 style="text-align: center;display: block;margin-top: 0;font-size: 20px">增项减项签证单</h3>
   <div style=" font-size: 18px;">委托方(简称甲方)：$user</div>
 
 <div style=" font-size: 18px;">施工方(简称乙方)：$company_name</div>
 <div style=" font-size: 18px; ">工程地址：$addres</div>
 <div style=" font-size: 18px; ">签约时间：$time</div>
           $s
           <p style=" font-size: 18px;">主合同管理费：$mainMoney 元</p>
           <p style=" font-size: 18px;">增项代购管理费：$money 元</p>
           <p style=" font-size: 18px;">优惠：$give_money 元</p>
           
 <p style=" font-size: 18px;">合计：$moneyS 元</p>
             <div style="border-top: 3px solid #0000"></div>
             
      
       
     
       <span style=" font-size: 18px;">甲方代表：      &ensp;&ensp;&ensp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;乙方代表：$username</span>
      
      <div></div>
       <span style=" font-size: 18px;">电话号码：$telephone&nbsp;&nbsp;&nbsp;&nbsp;电话号码:$phone</span>
       
       
      
       





       
      
</div>


</html>
EOF;
            
            
            require_once ROOT_PATH . 'extend/TCPDF/tcpdf.php';
            $pdf=new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
            $pdf->SetCreator('益鸟');
            
            
            $pdf->SetAuthor('益鸟 维修');
            $pdf->SetTitle('增项减项签证单');
            
            
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
            $pdf->setFontSubsetting(true);
            $pdf->SetPrintHeader(false);
            $pdf->SetPrintFooter(false);
            $pdf->SetFont('stsongstdlight', '', 20, true);
            $pdf->setCellPaddings(5, 7, 5, 20);
            $pdf->AddPage();
            
            $pdf->writeHTMLCell(0, 90, '', '', $html, 0, 0, 0, true, '', true);
            $pdf->Line(55, 10, 200, 10, ['width'=>0.1, 'cap'=>'butt', 'join'=>'miter', 'dash'=>'0', 'phase'=>10, 'color'=>[255, 255, 255]]);
            $pdf->Line(60, 47, 200, 47, ['width'=>0.1, 'cap'=>'butt', 'join'=>'miter', 'dash'=>'0', 'phase'=>10, 'color'=>[100, 100, 100]]);
            $pdf->Line(60, 62, 200, 62, ['width'=>0.1, 'cap'=>'butt', 'join'=>'miter', 'dash'=>'0', 'phase'=>10, 'color'=>[100, 100, 100]]);
            $pdf->Line(40, 77, 200, 77, ['width'=>0.1, 'cap'=>'butt', 'join'=>'miter', 'dash'=>'0', 'phase'=>10, 'color'=>[100, 100, 100]]);
            $pdf->Line(40, 95, 200, 95, ['width'=>0.1, 'cap'=>'butt', 'join'=>'miter', 'dash'=>'0', 'phase'=>10, 'color'=>[100, 100, 100]]);
            $pdf->Line(15, 105, 200, 105, ['width'=>1, 'cap'=>'butt', 'join'=>'miter', 'dash'=>'0', 'phase'=>10, 'color'=>[100, 100, 100]]);
            $pdf->SetAlpha(1);
            
            if(empty($company_chapter['company_chapter'])){
                $company_chapter['company_chapter']='http://yiniao.oss-cn-shenzhen.aliyuncs.com/public/chapter/chapter_yn.png';
            }
            $pdf->Image($company_chapter['company_chapter'], 140, 35, 50, 50, '', '', '', false, 300, '', false, false, 0);
            
            
            $pas=ROOT_PATHS . '/uploads/PDF/' . $order_id . '.pdf';
            $pdf->Output($pas, 'F');
            
            $o=$this->pdf2png($pas, ROOT_PATHS . '/uploads/PDF/', $order_id);
            
            if (file_exists(ROOT_PATHS . '/uploads/PDF/' . $order_id . '.png')) {
                unlink($pas);
            }
            
            return ['img'=>$o,'capital_id'=>array_column($io,'capital_id')];
        }else{
            return false;
        }
        
        
        
    }
    
    
    public function pdf2png($pdf, $path, $order_id)
    {
        try {
            
            $im=new \Imagick();
            $im->setCompressionQuality(100);
            $im->setResolution(120, 120);//设置分辨率 值越大分辨率越高
            
            $im->readImage($pdf);
            
            $canvas=new \Imagick();
            $imgNum=$im->getNumberImages();
            //$canvas->setResolution(120, 120);
            foreach ($im as $k=>$sub) {
                $sub->setImageFormat('png');
                //$sub->setResolution(120, 120);
                $sub->stripImage();
                $sub->trimImage(0);
                $width =$sub->getImageWidth() + 10;
                $height=$sub->getImageHeight() + 10;
                if ($k + 1 == $imgNum) {
                    $height+=10;
                } //最后添加10的height
                $canvas->newImage($width, $height, new \ImagickPixel('white'));
                $canvas->compositeImage($sub, \Imagick::COMPOSITE_DEFAULT, 5, 5);
            }
            
            $canvas->resetIterator();
            $canvas->appendImages(true)->writeImage($path . $order_id . '.png');
            return request()->domain() . '/' . config('city')  . '/uploads/PDF/' . $order_id . '.png?t=' . time();
//            return request()->domain() .config('city'). '/uploads/PDF/' . $order_id . '.png?t=' . time();
        } catch (Exception $e) {
            throw $e;
        }
        
        
    }
    
    public function cutChineseString($string, $length = 3) {
        if (mb_strlen($string) >= $length) {
            // 截取前5个字符
            $cutString = mb_substr($string, 0, $length);
            // 在截取的字符后面加上冒号
            return $cutString . '....';
        } else {
            // 如果字符串长度不超过指定长度，则直接返回
            return $string;
        }
    }
    
}